#include "tslib.h"
#include <stdio.h>
#include <linux/input.h>
#include <stdlib.h>
#include <sys/ioctl.h>

//ts_oepn
//ts_setup
//ts_close ts_config


//ts_read ts_read_mt

//struct ts_sample {
//  int x; //X 坐标
//  int y; //Y 坐标
//  unsigned int pressure; //按压力大小
//  struct timeval tv; //时间
// };
// struct ts_sample_mt {
//  /* ABS_MT_* event codes. linux/include/uapi/linux/input-event-codes.h
//  * has the definitions.
//  */
//  int x; //X 坐标
//  int y; //Y 坐标
//  unsigned int pressure; //按压力大小
//  int slot; //触摸点 slot
//  int tracking_id; //ID
// }
int main(int argc,char* argv[])
{
    struct tsdev *ts = NULL;
    struct ts_sample_mt *mt_ptr = NULL;
    struct input_absinfo slot;
    int max_slots;
    unsigned int pressure[12] = {0};    //用于保存每一个触点上一次的按压力

    int i;

    /* 打开并配置触摸屏设备*/
    ts = ts_setup(NULL,0);
    if(NULL == ts) {
        fprintf(stderr,"ts_setup error");
        exit(EXIT_FAILURE);
    }
     /* 获取触摸屏支持的最大触摸点数 */
    if (0 > ioctl(ts_fd(ts), EVIOCGABS(ABS_MT_SLOT), &slot)) {
        perror("ioctl error");
        ts_close(ts);
        exit(EXIT_FAILURE);
    }
    max_slots = slot.maximum + 1 - slot.minimum;
    printf("max_slots: %d\n", max_slots);
    mt_ptr = calloc(max_slots,sizeof(struct ts_sample_mt));

    for(;;) {
        if(0 > ts_read_mt(ts,&mt_ptr,max_slots,1)) {
            perror("ts_read_mt error");
            ts_close(ts);
            free(mt_ptr);
            exit(EXIT_FAILURE);
        }
        for (i = 0; i < max_slots; i++) {
            if (mt_ptr[i].valid) {//有效表示有更新!
                if (mt_ptr[i].pressure) { //如果按压力>0
                    if (pressure[mt_ptr[i].slot])//如果上一次的按压力>0
                        printf("slot<%d>, 移动(%d, %d)\n", mt_ptr[i].slot, mt_ptr[i].x, mt_ptr[i].y);
                    else
                        printf("slot<%d>, 按下(%d, %d)\n", mt_ptr[i].slot, mt_ptr[i].x, mt_ptr[i].y);
                }
                else
                    printf("slot<%d>, 松开\n", mt_ptr[i].slot);
                pressure[mt_ptr[i].slot] = mt_ptr[i].pressure;
            }
        }
    }
    ts_close(ts);
    free(mt_ptr);
    exit(EXIT_SUCCESS);
}